package com.thunbu.lib_common.utils.okhttp.cookie.store;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import okhttp3.Cookie;
import okhttp3.HttpUrl;

/**
 * Created by zhy on 16/3/10.
 */
public class MemoryCookieStore implements CookieStore {
    private final ConcurrentHashMap<String, List<Cookie>> allCookies = new ConcurrentHashMap<>();

    @Override
    public void add(HttpUrl url, List<Cookie> cookies) {
        List<Cookie> oldCookies = Collections.synchronizedList(allCookies.get(url.host()));
        List<Cookie> needRemove = Collections.synchronizedList(new ArrayList());
        if(oldCookies != null){
            for (Cookie newCookie : cookies) {
                for (Cookie oldCookie : oldCookies) {
                    if (newCookie.name().equals(oldCookie.name())) {
                        needRemove.add(oldCookie);
                    }
                }
            }
            oldCookies.removeAll(needRemove);
        }else {
            oldCookies = Collections.synchronizedList(new ArrayList());
            allCookies.put(url.host(),oldCookies);
        }
        oldCookies.addAll(cookies);
    }

    @Override
    public List<Cookie> get(HttpUrl uri) {
        List<Cookie> cookies = allCookies.get(uri.host());
        if (cookies == null) {
            cookies = Collections.synchronizedList(new ArrayList());
            allCookies.put(uri.host(), cookies);
        }
        return cookies;

    }

    @Override
    public boolean removeAll() {
        allCookies.clear();
        return true;
    }

    @Override
    public List<Cookie> getCookies() {
        List<Cookie> cookies = new ArrayList<>();
        Set<String> httpUrls = allCookies.keySet();
        for (String url : httpUrls) {
            cookies.addAll(allCookies.get(url));
        }
        return cookies;
    }


    @Override
    public boolean remove(HttpUrl uri, Cookie cookie) {
        List<Cookie> cookies = allCookies.get(uri);
        if (cookie != null) {
            return cookies.remove(cookie);
        }
        return false;
    }

}
